import { BASE_URL } from './config';
import axios from 'axios';
import qs from 'qs';
import { useAuthStore } from '../stores';
import { useNavigate } from 'react-router-dom';
const instance = axios.create({
  baseURL: /127|local/ig.test(location.host) ? '' : BASE_URL,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
});

instance.interceptors.request.use((config) => {
  // 处理请求前的逻辑
  if (config.headers['Content-Type'] === 'application/json') {
  if( config.method=="delete"){
    config.data =config.data
  }
  else{
    qs.parse(qs.stringify(config.data, { skipNulls: true }));
  }
  }

  const { token } = useAuthStore.getState();

  //if (token) {
    console.log(token, 'oooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii');
    config.headers['Authorization'] = token || '';
 // }

  return config;
});

instance.interceptors.response.use(
  (response) => {
    // 处理响应数据
    if (response.headers['Content-Type'] === 'application/json') {
      response.data = qs.parse(qs.stringify(response.data, { skipNulls: true }));
    }

    const { token } = useAuthStore.getState();

    if (token) {
      console.log(token, 'oooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii');
      response.headers['CLOUD-TOKEN'] = token || '';
    }

    return response.data; // 返回响应数据
  },
  (error) => {
    console.log('错误啦啦啦啦啦啦');
    
    // const navigate = useNavigate();
    // navigate('/login')

    // 处理响应错误
    return Promise.reject(error);
  }
);

export default instance;
